﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CanDoo;
using CanDoo.Core;
using CanDoo.Core.Data;
using CanDoo.Data;
using CanDoo.Extensions;
using CanDoo.Oil.Core.Contracts;
using CanDoo.Oil.Core.DTOs;
using CanDoo.Oil.Core.Models;
using CanDoo.Extensions;
using System.Threading.Tasks;
using System.Data.Entity;

namespace CanDoo.Oil.Core.Services
{
    /// <summary>
    /// 业务实现——售油机序列号
    /// </summary>
    public class OilSalesSerialNumService : CanDoo.Data.Entity.Services.ServiceBase<OilSalesSerialNum>, IOilSalesSerialNumContract
    {

        /// <summary>
        /// 业务契约——油品序列号
        /// </summary>
        public IOilSerialNumContract OilSerialNumContract { get; set; }
        public ICustomerContract CustomerContract { get; set; }
        public IProductContract ProductContract { get; set; }
        public IAPIOperateLogContract APIOperateLogContract { get; set; }

        public IBindDeviceContract BindDeviceContract { get; set; }
        public OilSalesSerialNumService()
        {
        
        }

        /// <summary>
        /// 新售油机接入门店时，门店与设备绑定
        /// </summary>
        /// <param name="deviceInfo">设备信息</param>
        /// <returns>操作结果</returns>
        public async Task<OperationResult> BindDeviceAsync(DeviceInfo deviceInfo)
        {
            using (var scope = DbScopeFactory.Create())
            {
                OperationResult result = OperationResult.NoChanged;
                //查询机器序列号是否存在
                //查询这个用户是否存在于机器序列号表
                //查询这个用户的属性 是不是售油机
                //查询这个型号 是不是售油机
                //都不存在 且是售油机 那就绑定

                //{ "storeNo":"333333","terminalNo":"5","type":"1234567","sn":"5"}

                if (deviceInfo.storeNo != deviceInfo.terminalNo)
                {
                    result.ResultType = OperationResultType.ValidError;
                    result.Message = "门店号和终端号必须相同";
                    return result;
                }

                var entity = await SingleOrDefaultAsync(p => p.SerialNumber == deviceInfo.sn);
                if(entity!=null )
                {
                    if (entity.TerminalNum == deviceInfo.terminalNo && entity.Product.SN == deviceInfo.type)
                    {
                        result.ResultType = OperationResultType.Success;
                        result.Message = "设备绑定验证成功";
                    }
                    else
                    {
                        result.ResultType = OperationResultType.ValidError;
                        result.Message = "系统中已存在此序列号的绑定信息,但门店号或设备型号不同";
                    }

                    //result.ResultType = OperationResultType.ValidError;
                    //result.Message = "系统中已存在此序列号的绑定信息";

                    //返回系统中已有的绑定信息
                    deviceInfo.storeNo = entity.Customer.CardNo;
                    deviceInfo.terminalNo = entity.TerminalNum;
                    deviceInfo.type = entity.Product.SN;
                    deviceInfo.sn = entity.SerialNumber;

                    return result;
                }

                entity = await SingleOrDefaultAsync(p => p.TerminalNum == deviceInfo.terminalNo);
                if (entity != null)
                {
                    //result.ResultType = OperationResultType.Success;
                    result.ResultType = OperationResultType.ValidError;
                    result.Message = "系统中已存在此终端号的绑定信息,请根据返回信息检查是否重复操作";

                    //返回系统中已有的绑定信息
                    deviceInfo.storeNo = entity.Customer.CardNo;
                    deviceInfo.terminalNo = entity.TerminalNum;
                    deviceInfo.type = entity.Product.SN;
                    deviceInfo.sn = entity.SerialNumber;

                    return result;
                }

                var product = await ProductContract.SingleOrDefaultAsync(p => p.SN== deviceInfo.type);
                if (product == null)
                {
                    result.ResultType = OperationResultType.ValidError;
                    result.Message = "设备型号在系统中不存在";
                    return result;
                }
                else
                {
                    if (product.ProductClass != 2)
                    {
                        result.ResultType = OperationResultType.ValidError;
                        result.Message = "此商品不是售油机";
                        return result;
                    }
                }

                var customer = await CustomerContract.SingleOrDefaultAsync(p => p.CardNo == deviceInfo.storeNo);
                if (customer == null)
                {
                    result.ResultType = OperationResultType.ValidError;
                    result.Message = "用户卡号在系统中不存在";
                    return result;
                }
                else
                {
                    if (customer.CardType != 3)
                    {
                        result.ResultType = OperationResultType.ValidError;
                        result.Message = "此卡不是售油机专用卡";
                        return result;
                    }
                    if(!customer.Status)
                    {
                        result.ResultType = OperationResultType.ValidError;
                        result.Message = "此卡未激活";
                        return result;
                    }
                }

                entity = new OilSalesSerialNum();
                entity.Id = IdMaker.NewId();
                entity.Name = product.Name;
                entity.SerialNumber = deviceInfo.sn;
                entity.BirthDay = null;
                entity.Batch = "";
                entity.ProductId = product.Id;
                entity.CustomerId = customer.Id;
                entity.TerminalNum = deviceInfo.terminalNo;
                entity.Secret = "";
                AddEntity(entity);

                
                var mEntity = new BindDevice();
                //mEntity.Id = IdMaker.NewId();
                mEntity.Name = "客户[" + deviceInfo.storeNo + "]绑定终端["+ entity.SerialNumber+"]";
                mEntity.UserId = customer.Id;
                mEntity.SerialNumber = entity.SerialNumber;
                mEntity.OperateTime = System.DateTime.Now;
                BindDeviceContract.AddEntity(mEntity);

                //#region 记录API操作日志
                //var mEntity = new APIOperateLog();
                //mEntity.Id = IdMaker.NewId();
                //mEntity.Name = "终端[" + deviceInfo.terminalNo + "]与客户["+ deviceInfo.storeNo+ "]绑定";
                //mEntity.OperateType = 1;
                //mEntity.OilSalerNo = entity.SerialNumber;
                //mEntity.OilPort = 0;
                //mEntity.BatchNo = "";
                //mEntity.OpreateTime = System.DateTime.Now;
                //mEntity.OilOutPut = 0;
                //mEntity.Before = 0.0;
                //mEntity.Last = 0.0;
                //mEntity.Price = 0.0;
                //mEntity.Money = 0.0;
                //mEntity.UpdateTime = null;
                //mEntity.Token = "";
                //mEntity.Status = 1;
                //mEntity.OilSalesSerialNumId = entity.Id;
                //mEntity.OilSerialNumId = null;
                //mEntity.Operater = "--";
                //mEntity.LinkEntityId = null;
                //mEntity.CustomerId = customer.Id;
                //APIOperateLogContract.AddEntity(mEntity);
                //#endregion


                result = await scope.SaveChangesAsync() > 0 ? OperationResult.Success : OperationResult.NoChanged;

                return result;

                //&& p.Customer.CardNo == deviceInfo.storeNo && p.Product.Code == deviceInfo.type
                //根据 门店号  机器条码 机型  找记录
                //var entity =await SingleOrDefaultAsync(p => p.SerialNumber == deviceInfo.sn);
                //if (entity == null)
                //{
                //    result.ResultType = OperationResultType.QueryNull;
                //    result.Message = "找不到记录,请提供正确的 机器条码";
                //}
                //else if (entity.Customer == null)
                //{
                //    result.ResultType = OperationResultType.ValidError;
                //    result.Message = "此机未出库";
                //}
                //else if (entity.Customer.CardNo.IsEmpty() || entity.Customer.CardNo != deviceInfo.storeNo)
                //{
                //    result.ResultType = OperationResultType.ValidError;
                //    result.Message = "此机不属于你";
                //}
                //else if (entity.Product.Code.IsEmpty() || entity.Product.Code != deviceInfo.type)
                //{
                //    result.ResultType = OperationResultType.ValidError;
                //    result.Message = "机型输入有误";
                //}
                //else if (string.IsNullOrEmpty(entity.TerminalNum) == false && entity.TerminalNum == deviceInfo.terminalNo)
                //{
                //    result.ResultType = OperationResultType.ValidError;
                //    result.Message = "重复绑定";
                //}
                //else if (string.IsNullOrEmpty(entity.TerminalNum) == false && entity.TerminalNum != deviceInfo.terminalNo)
                //{
                //    result.ResultType = OperationResultType.ValidError;
                //    result.Message = "终端编号与序列号与已有绑定不一致";
                //}
                //else if (CheckExists(p => p.TerminalNum == deviceInfo.terminalNo, entity.Id))
                //{
                //    result.ResultType = OperationResultType.ValidError;
                //    result.Message = "终端已被绑定";
                //}
                //else
                //{
                //    entity.TerminalNum = deviceInfo.terminalNo;
                //    UpdateEntity(entity);
                //    result = await scope.SaveChangesAsync() > 0 ? OperationResult.Success : OperationResult.NoChanged;
                //}
                //return result;
            }
        }

        /// <summary>
        /// 获取1.1.2获取售油配置信息
        /// </summary>
        /// <param name="keyInfo">门店号,终端号</param>
        /// <returns>如果找不到信息,返回null</returns>
        public async Task<SellingConfigInfo> GetSellingConfigInfoAsync(TerminalKeyInfo keyInfo)
        {
            using (DbScopeFactory.CreateReadOnly())
            {
                var customer = CustomerContract.SingleOrDefault(p => p.CardNo == keyInfo.storeNo);
                if (customer == null)
                    throw new ArgumentException($"门店号storeNo={keyInfo.storeNo}的客户不存在");

                var entity = SingleOrDefault(p => p.TerminalNum == keyInfo.terminalNo);//p.CustomerId == customer.Id && 
                if (entity == null)
                {
                    throw new ArgumentException($"终端号TerminalNum={keyInfo.terminalNo}的售油机不存在");
                }

                SellingConfigInfo data = new SellingConfigInfo();

                var oilConfigList =await OilSerialNumContract.Entities.Where(p => p.CustomerId == customer.Id && p.Status == OilSerialStatus.OnSale).ToListAsync();
                if(oilConfigList.Count() == 0)
                {
                    throw new KeyNotFoundException("此终端查不到油桶信息");
                }
                if (oilConfigList != null)
                {
                    var list = new List<Oillist>();
                    foreach (var m in oilConfigList)
                    {
                        Oillist oilList = new Oillist();
                        oilList.terminalId = entity.TerminalNum;
                        oilList.id = customer.CardNo;
                        oilList.oilName = m.Product.Name;
                        oilList.stock = m.LastOil.ToInt();
                        oilList.prize = (m.Product.RetailPrice * 100).ToInt();
                        oilList.oilPort = m.OilPort;//出油口
                        oilList.grade = m.Product.Specifications; //油品等级
                        oilList.oilId = m.Product.SN; //油的内部编码
                        oilList.oilUrl =  m.Product.ImgUrl1.Replace("~/","http://" + HttpContext.Current.Request.Url.Host + "/");//油品图片
                        list.Add(oilList);
                    }
                    data.oilList = list.ToArray();
                }

                AdminCardlist adminCardList = new AdminCardlist();
                data.adminCardList = new[] { adminCardList }; //OilSalesSerialNum表 根据CustomerId找到客户  然后把客户的数据写过去
                                                              //adminCardList.id = 
                adminCardList.cardNo = entity.Customer.CardNo;//
                adminCardList.status = entity.Customer.Status == true ? 0 : 1;//0能用  1不能用
                adminCardList.cardHolder = entity.Customer.CardName;//
                adminCardList.phone = entity.Customer.MobilePhone;//
                                                                  //adminCardList.cardPwd = entity.Customer.Password;// 空//这个密码什么用的?
                adminCardList.createTime = entity.Customer.CreatedTime.TimeToString("yyyy-MM-dd HH:mm:ss");//
                adminCardList.updateTime = entity.Customer.LastUpdatedTime.TimeToString("yyyy-MM-dd HH:mm:ss");//

                return data;
            }
        }

        /// <summary>
        /// 获取售油机信息 用于oauth认证
        /// </summary>
        /// <param name="clientId">机器条码</param>
        /// <param name="clientSecret">门店号</param>
        /// <returns></returns>
        public async Task<OilSalesSerialNum> GetByClientAsync(string clientId, string clientSecret)
        {
            using (DbScopeFactory.CreateReadOnly())
            {
                var entity = await GetByClientAsync(clientId);
                if (entity == null)
                    throw new CanDoo.Exceptions.CanDooException($"终端号为{clientId}的售油机找不到");
                return entity;

                //if ((string.IsNullOrEmpty(entity.Secret) && "1" == clientSecret) || entity.Secret == clientSecret)
                //    return entity;
                //throw new CanDoo.Exceptions.CanDooException($"终端号为{clientId}的售油机密钥验证失败");
            }
        }

        /// <summary>
        /// 获取售油机信息 用于oauth认证
        /// </summary>
        /// <param name="clientId">终端号</param>
        /// <returns></returns>
        public async Task<OilSalesSerialNum> GetByClientAsync(string clientId)
        {
            using (DbScopeFactory.CreateReadOnly())
            {
                return await SingleOrDefaultAsync(p => p.TerminalNum == clientId);
            }
        }


        /// <summary>
        /// 1.1.16门店终端信息 根据门店和终端编号，获取终端信息
        /// </summary>
        /// <param name="terminalKeyInfo"></param>
        /// <returns></returns>
        public async Task<TerminalInfo> GetTerminalInfoAsync(TerminalKeyInfo terminalKeyInfo)
        {
            using (DbScopeFactory.CreateReadOnly())
            {
                return await Entities.Where(p => p.TerminalNum == terminalKeyInfo.terminalNo)
                    .Select(p => new TerminalInfo { terminalNo = p.TerminalNum, storeNo = p.Customer.CardNo, sn = p.SerialNumber })
                    .FirstOrDefaultAsync();
            }
        }

        public async Task<OilSalesSerialNum> GetByTerminalNoAsync(string terminalNo)
        {
            return await SingleOrDefaultAsync(p => p.TerminalNum == terminalNo);
        }
    }
}
